<?php

/**
 * Description of DALUserAccount
 *
 * @author aethv
 */
class DALUserAccount extends DALBase{
    
    
    public function __construct() {
        parent::__construct();
        $this->_tbl = 'user_account';
        $this->_key = 'id';
    }
    
    public function loginUser($user, $pass){
        $data = array();
        
        $user = Utils::escape($user);
        $pass = Utils::escape($pass);
        
        $query = "SELECT * FROM $this->_tbl WHERE username='$user' and password='$pass'";
        $result = $this->executeQuery($query);
        echo $query;
        if ($result) {
            //  Scan through the resource
            while ($row = mysql_fetch_object($result)) {
                //  put row object into the array
                $data[] = $row;
            }
        }
        if(count($data) > 0){
            return $data[0];
        }
        return false;
    }
    
    public function getUser(){
        $id = $_SESSION['id'];
        
        $conn = $this->_getConnection();
        $result = $this->getByID($id);
        if($result){
            return $result;
        }
        $this->closeDB($conn);     
        return false;
    }
    
    public function getCurrentBalance(){
        $id = $_SESSION['id'];
        
        $conn = $this->_getConnection();
        $result = $this->getByID($id);
        if($result){
            return $result['balance'];
        }
        $this->closeDB($conn);     
        return 'not found';
    }
    
    public function updateBalance($id, $balance){
        $result = $this->getByID($id);
        if(!$result){
            return -1;
        }
        $query = 'UPDATE user_account SET balance=' . $balance . ' WHERE id=' . $id;
        $Status = $this->executeQuery($query);
        if(!$Status){
            return 0;
        }else{
            return 1;
        }
        return -1;
    }
    
    public function updateAppStatus($id, $status){
        $result = $this->getByID($id);
        if(!$result){
            return 'user not found';
        }
        $query = "UPDATE user_account SET active=$status WHERE id=$id";
        $status = $this->executeQuery($query);
        if($status){
            $q = "SELECT count(1) FROM settled_contract WHERE running = TRUE";
            $ret = $this->executeQuery($q);
            if($ret){
                $row = mysql_fetch_array($ret);
                return $row[0];
            }
        }else{
            return 'user not found';
        }
    }
}
